package com.wonder.app.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.constant.IVtuzxConst;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.admin.service.IVtuzxKingdeeService;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.*;
import com.wonder.app.service.*;
import com.wonder.bean.kingdee.VtuzxKingdeeCloudClient;
import com.wonder.bean.kingdee.xqc.ConvertDate;
import com.wonder.bean.kingdee.xqc.VtuzxArrayList;
import com.wonder.common.utils.DateUtils;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class KingdeeBasicServiceImpl implements KingdeeBasicService {

    /**
     * 物料
     */
    @Autowired
    private MaterialDao materialDao;
    @Autowired
    private IVtuzxKingdeeService kingdeeService;

    @Autowired
    private MaterialService materialService;

    @Autowired
    private SynbdDao synbdDao;
    @Autowired
    private SynbdService synbdService;
    @Autowired
    private ConvertDate convertDate;

    @Autowired
    private StockListDao stockListDao;

    @Autowired
    private StockListService stockListService;

    @Autowired
    private IpadUserService ipadUserService;

    @Autowired
    private IpadUserDao ipadUserDao;




    @Override
    public void syncMaterial(String endTime) throws Exception {
        syncMaterial(0, 50,endTime);
    }

    @Override
    public void syncStockList(String endTime) throws Exception {
        syncStockList(0, 50,endTime);
    }

    @Override
    public void syncBom(String endTime) throws Exception {
        syncBom(0,50,endTime);
    }

    @Override
    public void syncUser(String endTime)  throws Exception{
        syncUser(0,50,endTime);
    }

    /**
     * 同步金蝶物料
     * @param start
     * @param limit
     * @param endTime 最后同步时间
     * @throws Exception
     */
    private void syncUser(int start, int limit,String endTime) throws Exception {
        String cond = String.format("FCreateDate > '%s' or FModifyDate > '%s'",endTime,endTime);
        VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
        List<VtuzxMap> userQuery = kingdeeService.query(client, "BD_Empinfo", new VtuzxArrayList<>(
                        "FName",//员工姓名
                        "FPostId",//所属岗位
                        "F_DLMH_FPBL",//分配比例
                        "F_DLMH_LK",//是否冷库
                        "F_DLMH_Base1.FName",//默认车间
                        "F_DLMH_JBGZ",//基本工资
                        "F_DLMH_JXGZ",//绩效工资
                        "F_DLMH_BZJX",//班长绩效
                        "F_DLMH_GWGZ",//岗位工资
                        "F_DLMH_ZFBT",//住房补贴
                        "F_DLMH_GLGZ",//工龄工资
                        "F_DLMH_BMGZ",//保密工资
                        "F_DLMH_BXBZ",//保险补助
                        "F_DLMH_QTBZ",//其他补助
                        "F_DLMH_QTBZBZ",//其他补助备注
                        "FPostDept.FNAME",//所属部门
                        "FForbidStatus",//禁用状态(A为未禁用,B为禁用)
                        "FStaffNumber"//员工编号
                ),
                "", "", start, limit);

        List<IpadUser> dataList = new ArrayList<>();
        for (VtuzxMap data : userQuery) {
             String userName = VtuzxUtil.getString(data,"FName");
             String FPostId = VtuzxUtil.getString(data,"FPostId");//所属岗位
             Double F_DLMH_FPBL = VtuzxUtil.getDouble(data,"F_DLMH_FPBL");//分配比例
             Boolean F_DLMH_LK = VtuzxUtil.getBoolean(data,"F_DLMH_FPBL");//是否冷库
             String F_DLMH_Base = VtuzxUtil.getString(data,"F_DLMH_Base1.FName");//默认车间
             Double F_DLMH_JBGZ = VtuzxUtil.getDouble(data,"F_DLMH_JBGZ");//基本工资
             Double F_DLMH_JXGZ = VtuzxUtil.getDouble(data,"F_DLMH_JXGZ");//绩效工资
             Double F_DLMH_BZJX = VtuzxUtil.getDouble(data,"F_DLMH_BZJX");//班长绩效
             Double F_DLMH_GWGZ = VtuzxUtil.getDouble(data,"F_DLMH_GWGZ");//岗位工资
             Double F_DLMH_ZFBT = VtuzxUtil.getDouble(data,"F_DLMH_ZFBT");//住房补贴
             Double F_DLMH_GLGZ = VtuzxUtil.getDouble(data,"F_DLMH_GLGZ");//工龄工资
             Double F_DLMH_BMGZ = VtuzxUtil.getDouble(data,"F_DLMH_BMGZ");//保密工资
             Double F_DLMH_BXBZ = VtuzxUtil.getDouble(data,"F_DLMH_BXBZ");//保险补助
             Double F_DLMH_QTBZ = VtuzxUtil.getDouble(data,"F_DLMH_QTBZ");//其他补助
             String F_DLMH_QTBZBZ = VtuzxUtil.getString(data,"F_DLMH_QTBZBZ");//其他补助备注
             String FStaffNumber = VtuzxUtil.getString(data,"FStaffNumber");//员工编号
             String postDept = VtuzxUtil.getString(data,"FPostDept.FNAME");//所属部门
             String FForbidStatus = VtuzxUtil.getString(data,"FStaffNumber");//禁用状态
            //先判断员工是否存在
            LambdaQueryWrapper<IpadUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(IpadUser::getUserNumber,FStaffNumber)
                    .eq(IpadUser::getFname,userName);
            IpadUser ipadUser = ipadUserService.getOne(wrapper);
            if (null != ipadUser){//当前员工存在
                ipadUser.setDepartment(F_DLMH_Base);
                ipadUser.setBasicPay(F_DLMH_JBGZ);
                ipadUser.setMeritPay(F_DLMH_JXGZ);
                ipadUser.setPostWage(F_DLMH_GWGZ);
                ipadUser.setWorkerPay(F_DLMH_GLGZ);
                ipadUser.setHouseSubsidy(F_DLMH_ZFBT);
                ipadUser.setPostSubsity(F_DLMH_BZJX);//班长绩效
                ipadUser.setInsurance(F_DLMH_BXBZ);//保险补助
                ipadUser.setDistribution(F_DLMH_FPBL);//分配比例
                ipadUser.setIsCold(F_DLMH_LK);
                ipadUser.setOtherSubsity(F_DLMH_QTBZ);
                ipadUser.setSecrecy(F_DLMH_BMGZ);
                ipadUser.setRemark(F_DLMH_QTBZBZ);
                ipadUser.setPost(FPostId);
                //如果部门是生产部的添加部门信息
                if("生产部".equals(postDept)){
                    ipadUser.setPostDept(postDept);
                }
                if ("A".equals(FForbidStatus)){
                    ipadUser.setForbidStatus(false);
                } else {
                    ipadUser.setForbidStatus(true);//禁用
                }

                dataList.add(ipadUser);
            } else {
                IpadUser user = new IpadUser();
                user.setUserNumber(FStaffNumber);
                user.setFname(userName);
                user.setDepartment(F_DLMH_Base);
                user.setBasicPay(F_DLMH_JBGZ);
                user.setMeritPay(F_DLMH_JXGZ);
                user.setPostWage(F_DLMH_GWGZ);
                user.setWorkerPay(F_DLMH_GLGZ);
                user.setHouseSubsidy(F_DLMH_ZFBT);
                user.setPostSubsity(F_DLMH_BZJX);//班长绩效
                user.setInsurance(F_DLMH_BXBZ);//保险补助
                user.setDistribution(F_DLMH_FPBL);//分配比例
                user.setIsCold(F_DLMH_LK);
                user.setOtherSubsity(F_DLMH_QTBZ);
                user.setSecrecy(F_DLMH_BMGZ);
                user.setRemark(F_DLMH_QTBZBZ);
                user.setPost(FPostId);
                //如果部门是生产部的添加部门信息
                if("生产部".equals(postDept)){
                    ipadUser.setPost(postDept);
                }
                if ("A".equals(FForbidStatus)){
                    ipadUser.setForbidStatus(false);
                } else {
                    ipadUser.setForbidStatus(true);//禁用
                }
                dataList.add(user);
            }
        }
        ipadUserService.saveOrUpdateBatch(dataList);


        if (userQuery.size() >= limit) {
            syncUser(start + limit, limit,endTime);
        }

    }
    /**
     * 同步金蝶物料
     * @param start
     * @param limit
     * @param endTime 最后同步时间
     * @throws Exception
     */
    private void syncMaterial(int start, int limit,String endTime) throws Exception {
        String cond = String.format("FCreateDate > '%s' or FModifyDate > '%s' and FUseOrgId.fnumber ='100' ",endTime,endTime);
        //String cond = String.format("FCreateOrgId.fnumber = '100' and FUseOrgId .fnumber = '100'");
        VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
        List<VtuzxMap> materialQuery = kingdeeService.query(client, "BD_MATERIAL", new VtuzxArrayList<>(
                        "FCreateOrgId.FName", //创建组织
                        "FUseOrgId1.FName",//使用组织
                        "FForbidStatus",//禁用状态
                        "FModifierId",//修改人
                        "FApproverId.fname",//审核人
                        "FApproveDate",//审核日期
                        "FIsBatchManage",//是否启用批号
                        "FIsKFPeriod",//是否启用保质期
                        "FModifyDate",//修改日期
                        "FName", //物料名称
                        "FOldNumber",//旧编码
                        "FNumber", //物料编码
                        "FSpecification", //规格
                        "FMaterialGroup.FNumber", //物料分组
                        "FMaterialGroup.FName", //物料分组
                        "FDocumentStatus", //数据状态
                        "FErpClsID", //物料属性
                        "FCreateDate", //创建修改日期
                        "FMATERIALID", //物料内码
                        "FBaseUnitId.FNumber", //基本单位编码
                        "FBaseUnitId.FName", //基本单位名称
                        "FCategoryID.FName", //存货类别
                        "FCreatorId",//创建人
                        "FExpPeriod",//保质期
                        "FExpUnit",//保质期单位
                        "FBaseProperty",//分组编码
                        "FStockId.fnumber",//仓库编码
                        "FStockId.fname"//仓库名称
                ),
                cond, "", start, limit);

        List<Material> dataList = new ArrayList<>();
        for (VtuzxMap data : materialQuery) {
            String materialId = VtuzxUtil.getString(data,"FMATERIALID");//物料内码
            String fNumber = VtuzxUtil.getString(data,"FNumber");//物料编码
            String fName = VtuzxUtil.getString(data,"FName");//物料名称
            String oldNumber  = VtuzxUtil.getString(data,"FOldNumber");//旧编码
            String specification  = VtuzxUtil.getString(data,"FSpecification");//规格
            Long materialGroup = VtuzxUtil.getLong(data,"FMaterialGroup.FNumber");//物料分组
            String createOrg = VtuzxUtil.getString(data,"FCreateOrgId.FName");//创建组织
            String useOrg = VtuzxUtil.getString(data,"FUseOrgId1.FName");//使用组织
            String createTime = VtuzxUtil.getString(data,"FCreateDate");//创建日期
            Date createDate = DateUtils.strToDate(createTime,"yyyy-MM-dd'T'HH:mm:ss");
            String modifier = VtuzxUtil.getString(data,"FModifierId");//修改人
            String modifyStr = VtuzxUtil.getString(data,"FModifyDate");//修改日期
            Date modifyDate = DateUtils.strToDate(modifyStr,"yyyy-MM-dd'T'HH:mm:ss");

            String status = VtuzxUtil.getString(data,"FDocumentStatus");//数据状态
            Boolean forbidStatus = VtuzxUtil.getBoolean(data,"FForbidStatus");//禁用状态
            String approver = VtuzxUtil.getString(data,"FApproverId.fname");//审核人
            String approveStr = VtuzxUtil.getString(data,"FApproveDate");//审核日期
            Date approveDate = DateUtils.strToDate(approveStr,"yyyy-MM-dd'T'HH:mm:ss");
            String createUserName = VtuzxUtil.getString(data,"FCreatorId");//创建人
            Boolean isFlot = VtuzxUtil.getBoolean(data,"FIsBatchManage");//是否启用批号
            Boolean isProduce = VtuzxUtil.getBoolean(data,"FIsKFPeriod");//是否启用保质期
            Integer expPeriod = VtuzxUtil.getInt(data,"FExpPeriod");//是否启用保质期
            String  expUnit = VtuzxUtil.getString(data,"FExpUnit");//是否启用保质期
            String  stockNo = VtuzxUtil.getString(data,"FStockId.fnumber");//仓库编码
            String  stockName = VtuzxUtil.getString(data,"FStockId.fname");//仓库名称


            //判断物料是否存在
            Material material1 = materialDao.selectOne(new QueryWrapper<Material>().eq("FNUMBER", fNumber));
            if(null != material1){
                material1.setFMATERIALID(materialId);
                material1.setFNUMBER(fNumber);
                material1.setFName(fName);
                material1.setFOLDNUMBER(oldNumber);
                material1.setFSPECIFICATION(specification);
                material1.setFMATERIALGROUP(materialGroup);
                material1.setFCREATEORG(createOrg);
                material1.setFUSEORG(useOrg);
                material1.setFCREATEDATE(createDate);
                material1.setFMODIFIER(modifier);
                material1.setFMODIFYDATE(modifyDate);
                material1.setFSTATUS(status);
                material1.setFFORBIDSTATUS(forbidStatus);//禁用状态
                material1.setFAPPROVER(approver);
                material1.setFAPPROVEDATE(approveDate);
                material1.setFIsFlot(isFlot);
                material1.setFIsProduce(isProduce);
                material1.setStockNo(stockNo);
                material1.setStockName(stockName);
                //如果启用保质期管理添加保质期信息
                if(isProduce){
                    material1.setExpperiod(expPeriod);
                    material1.setExpUnit(expUnit);
                }
                material1.setFCREATEUSERNAME(createUserName);
                dataList.add(material1);
            } else {
                Material material = new Material();
                material.setFMATERIALID(materialId);
                material.setFNUMBER(fNumber);
                material.setFName(fName);
                material.setFOLDNUMBER(oldNumber);
                material.setFSPECIFICATION(specification);
                material.setFMATERIALGROUP(materialGroup);
                material.setFCREATEORG(createOrg);
                material.setFUSEORG(useOrg);
                material.setFCREATEDATE(createDate);
                material.setFMODIFIER(modifier);
                material.setFMODIFYDATE(modifyDate);
                material.setFSTATUS(status);
                material.setFFORBIDSTATUS(forbidStatus);//禁用状态
                material.setFAPPROVER(approver);
                material.setFAPPROVEDATE(approveDate);
                material.setFIsFlot(isFlot);
                material.setFIsProduce(isProduce);
                material.setStockNo(stockNo);
                material.setStockName(stockName);
                //如果启用保质期管理添加保质期信息
                if(isProduce){
                    material.setExpperiod(expPeriod);
                    material.setExpUnit(expUnit);
                }
                material.setFCREATEUSERNAME(createUserName);
                //TODO 缺少工资分配系数,净重计件还是毛重计件,质检入库未质检入库
                dataList.add(material);
            }



        }
        if(dataList.size() > 0){
            boolean b = materialService.saveOrUpdateBatch(dataList);
        }

        if (materialQuery.size() >= limit) {
            syncMaterial(start + limit, limit,endTime);
        }

    }

    private void syncStockList(int start , int limit , String endTime) throws Exception{
        String cond = String.format("FCreateDate > '%s' or FModifyDate > '%s'",endTime,endTime);
        VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
        List<VtuzxMap> stockQuery = kingdeeService.query(client, "BD_STOCK", new VtuzxArrayList<>(
                        "FStockId", //仓库内码
                            "FNumber",//仓库编码
                            "FName",//仓库名称
                            "FGroup",//仓库分组
                "FUseOrgId.FName",//使用组织
                "FCreateDate",//创建日期
                "FModifyDate",//修改日期
                "FDocumentStatus",//数据状态
                "FForbidStatus"//禁用状态
                ),
                cond, "", start, limit);

        List<StockList> dataList = new ArrayList<>();
        for (VtuzxMap data : stockQuery) {
            Long stockId = VtuzxUtil.getLong(data,"FStockId");//仓库内码
            String fNumber = VtuzxUtil.getString(data,"FNumber");//仓库编码
            String fName = VtuzxUtil.getString(data,"FName");//仓库名称
            String group = VtuzxUtil.getString(data,"FGroup");//库存分组
            String useOrg = VtuzxUtil.getString(data,"FUseOrgId.FName");//使用组织
            String documentStatus = VtuzxUtil.getString(data,"FDocumentStatus");//数据状态
            String forbidStatus = VtuzxUtil.getString(data,"FForbidStatus");//禁用状态
            String createStr = VtuzxUtil.getString(data,"FCreateDate");//创建日期
            Date createDate = DateUtils.strToDate(createStr,"yyyy-MM-dd'T'HH:mm:ss");
            String modifyStr = VtuzxUtil.getString(data,"FModifyDate");//修改日期
            Date modifyDate = DateUtils.strToDate(modifyStr,"yyyy-MM-dd'T'HH:mm:ss");

            //先查询仓库是否存在
            StockList stockList = stockListDao.selectOne(new QueryWrapper<StockList>().eq("FNumber", fNumber));
            if (null != stockList){
                stockList.setFStockId(stockId);
                stockList.setFNumber(fNumber);
                stockList.setFName(fName);
                stockList.setFGroup(group);
                stockList.setFUseOrgId(useOrg);
                stockList.setFCreateDate(createDate);
                stockList.setFModifyDate(modifyDate);
                stockList.setFDocumentStatus(documentStatus);
                stockList.setFForbidStatus(forbidStatus);
                dataList.add(stockList);
            } else {
                StockList addDetail = new StockList();
                addDetail.setFStockId(stockId);
                addDetail.setFNumber(fNumber);
                addDetail.setFName(fName);
                addDetail.setFGroup(group);
                addDetail.setFUseOrgId(useOrg);
                addDetail.setFCreateDate(createDate);
                addDetail.setFModifyDate(modifyDate);
                addDetail.setFDocumentStatus(documentStatus);
                addDetail.setFForbidStatus(forbidStatus);
                dataList.add(stockList);
                stockListService.save(addDetail);
            }

        }
//        if(dataList.size() > 0){
//            boolean b = stockListService.saveOrUpdateBatch(dataList);
//        }

        if (stockQuery.size() >= limit) {
            syncMaterial(start + limit, limit,endTime);
        }
    }

    private void syncBom(int start , int limit , String endTime) throws Exception {
    }
}
